package com.dmap.admin.controller.backgroundv2;

import com.dmap.admin.bo.backgroundv2.CompanyBo;
import com.dmap.admin.constants.AdminConstant;
import com.dmap.admin.controller.backgroundv2.param.CompanyAndUserV2Param;
import com.dmap.admin.controller.backgroundv2.param.CompanySelectParam;
import com.dmap.admin.controller.backgroundv2.param.UserV2Param;
import com.dmap.admin.po.Company;
import com.dmap.admin.service.backgroundv2.CompanyService;
import com.dmap.admin.service.backgroundv2.UserV2Service;
import com.dmap.admin.vo.backgroundv2.RecordNumAndCompanyVo;
import com.dmap.base.constants.Constant;
import com.dmap.base.vo.BaseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * \* User: helei
 * \* Date: 02/05/18
 * \* Description:
 * \
 */
@Api(value = "公司管理", description = "background/公司管理")
@Controller
@RequestMapping(value = "/background/pmpd-admin-server/v2/company/")
public class CompanyController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private UserV2Controller userV2Controller;
    @Resource
    private CompanyService companyService;
    @Resource
    private UserV2Service userV2Service;

    @ResponseBody
    @ApiOperation(value = "新增 company/管理员二合一接口",
            notes = "1. 必填： 公司编号number, 公司名称name, 联系电话companyPhone, " +
                    "项目地址province, city, ownedByCompanyId, creatorId; " +
                    "2. 返回companyId;")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public BaseVo insert(@RequestBody CompanyAndUserV2Param param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getNumber()) || StringUtils.isBlank(param.getName())
                || StringUtils.isBlank(param.getCompanyPhone())
                || StringUtils.isBlank(param.getProvince()) || StringUtils.isBlank(param.getCity())
                || StringUtils.isBlank(param.getOwnedByCompanyId()) || !StringUtils.isNumeric(param.getOwnedByCompanyId())
                || Long.valueOf(param.getOwnedByCompanyId()).equals(0L)
                || StringUtils.isBlank(param.getCreatorId()) || !StringUtils.isNumeric(param.getCreatorId())
                || Long.valueOf(param.getCreatorId()).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        //验证公司编号/名称/管理员ID是否已存在
        boolean paramIsExist = companyService.validateNumberOrNameOrAdministratorIdIsExist(param.getNumber(), param.getName(), param.getAdministratorId());
        if (paramIsExist) {
            baseVo.setCode(AdminConstant.RESPONSE_COMPANY_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_COMPANY_ERROR_MSG);
            return baseVo;
        }
        //如果管理员ID参数为空，则先插入一个管理员
        if (StringUtils.isBlank(param.getAdministratorId()) || !StringUtils.isNumeric(param.getAdministratorId())
                || Long.valueOf(param.getAdministratorId()).equals(0L)) {
            if (param.getUserV2Param() == null) {
                baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
                baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
                return baseVo;
            }
            param.getUserV2Param().setStatus(AdminConstant.NORMAL_STATUS);
            param.getUserV2Param().setUserType(AdminConstant.USER_TYPE_COMPANY_ADMIN);
            BaseVo baseVo1 = userV2Controller.insert(param.getUserV2Param());
            if (!baseVo1.getCode().equals(Constant.RESPONSE_SUCCESS_CODE)) {
                baseVo.setCode(baseVo1.getCode());
                baseVo.setMsg(baseVo1.getMsg());
                return baseVo;
            }
            //刚新插入的管理员返回的ID做为该公司的管理员ID
            param.setAdministratorId(baseVo1.getData().toString());
            param.setAdministratorAccount(param.getUserV2Param().getAccount());
            param.setAdministratorHandphone(param.getUserV2Param().getHandphone());
        }
        param.setCompanyType(AdminConstant.COMPANY_TYPE_BRANCH);
        Company company = companyService.insertCompany(param);
        if (company == null) {
            baseVo.setCode(Constant.RESPONSE_INSERT_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_INSERT_ERROR_MSG);
            return baseVo;
        }
        //将上面插入的管理员的所在公司信息更新为刚插入的公司信息
        UserV2Param userV2Param = new UserV2Param();
        userV2Param.setId(param.getAdministratorId());
        userV2Param.setCompanyId(company.getId().toString());
        userV2Param.setCompanyName(param.getName());
        userV2Param.setCompanyType(param.getCompanyType());
        userV2Param.setUserType(AdminConstant.USER_TYPE_COMPANY_ADMIN);
        userV2Param.setStatus(AdminConstant.NORMAL_STATUS);
        userV2Param.setDeleteStatus(AdminConstant.DELETE_STATUS_NORMAL);
        userV2Service.updateUser(userV2Param);

        baseVo.setData(company.getId().toString());
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "修改 company",
            notes = "1. 必填： id, 编号number, 名称name, 联系电话companyPhone, 管理员administratorId, " +
                    "项目地址province, city, ownedByCompanyId;")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public BaseVo update(@RequestBody CompanyAndUserV2Param param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || StringUtils.isBlank(param.getId()) || !StringUtils.isNumeric(param.getId())
                || Long.valueOf(param.getId()).equals(0L) || StringUtils.isBlank(param.getNumber())
                || StringUtils.isBlank(param.getName()) || StringUtils.isBlank(param.getCompanyPhone())
                || StringUtils.isBlank(param.getAdministratorId()) || !StringUtils.isNumeric(param.getAdministratorId())
                || Long.valueOf(param.getAdministratorId()).equals(0L)
                || StringUtils.isBlank(param.getProvince()) || StringUtils.isBlank(param.getCity())
                || StringUtils.isBlank(param.getOwnedByCompanyId()) || !StringUtils.isNumeric(param.getOwnedByCompanyId())
                || Long.valueOf(param.getOwnedByCompanyId()).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        //更新管理员之后，将原先的管理员所在公司ID置为0
        Company previousCompany = companyService.selectById(Long.valueOf(param.getId()));
        if (previousCompany != null && previousCompany.getAdministratorId() != null) {
            UserV2Param userV2Param = new UserV2Param();
            userV2Param.setId(previousCompany.getAdministratorId().toString());
            userV2Param.setCompanyId("0");
            userV2Param.setStatus(AdminConstant.FORBID_STATUS);
            userV2Param.setDeleteStatus(AdminConstant.DELETE_STATUS_DELETED);
            userV2Service.updateUser(userV2Param);
        }
        boolean success;
        try {
            success = companyService.updateCompany(param);
        } catch (RuntimeException e) {
            //如果用户修改公司编号/名称/管理员id是已存在的，则提示唯一
            logger.error(e.getMessage());
            baseVo.setCode(AdminConstant.RESPONSE_COMPANY_ERROR_CODE);
            baseVo.setMsg(AdminConstant.RESPONSE_COMPANY_ERROR_MSG);
            return baseVo;
        }
        if (!success) {
            baseVo.setCode(Constant.RESPONSE_UPDATE_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_UPDATE_ERROR_MSG);
        }
        //更新公司之后，同步更新该公司当前管理员所在的公司信息
        UserV2Param userV2Param = new UserV2Param();
        userV2Param.setId(param.getAdministratorId());
        userV2Param.setCompanyId(param.getId());
        userV2Param.setCompanyName(param.getName());
        userV2Param.setCompanyType(param.getCompanyType());
        userV2Param.setUserType(AdminConstant.USER_TYPE_COMPANY_ADMIN);
        userV2Param.setStatus(AdminConstant.NORMAL_STATUS);
        userV2Param.setDeleteStatus(AdminConstant.DELETE_STATUS_NORMAL);
        userV2Service.updateUser(userV2Param);

        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据administratorId查询其所在公司信息", notes = "必填： administratorId")
    @RequestMapping(value = "select/selectByAdministratorId", method = RequestMethod.GET)
    public BaseVo selectByAdministratorId(@RequestParam String administratorId) {
        BaseVo baseVo = new BaseVo();
        if (StringUtils.isBlank(administratorId) || !StringUtils.isNumeric(administratorId)
                || Long.valueOf(administratorId).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        Company company = companyService.selectByAdministratorId(Long.valueOf(administratorId));
        if (company == null) {
            return baseVo;
        }
        CompanyBo companyBo = new CompanyBo(company);
        baseVo.setData(companyBo);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据参数查询公司，和模糊查询、排序是一个接口",
            notes = "1. 必填： companyType; " +
                    "2. 必填：pageIndex(>=1), pageSize(>=1); " +
                    "3. 返回company列表; ")
    @RequestMapping(value = "select/selectByExample", method = RequestMethod.POST)
    public BaseVo selectByExample(@RequestBody CompanySelectParam param) {
        BaseVo baseVo = new BaseVo();
        if (param == null || param.getCompanyType() == null
                || param.getCompanyType() != AdminConstant.COMPANY_TYPE_HEAD
                || param.getPageIndex() == null || param.getPageSize() == null
                || param.getPageIndex() < 1 || param.getPageSize() < 1) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        int recordNum = companyService.countByCompanySelectParam(param);
        List<CompanyBo> boList = new ArrayList<>();
        if (recordNum > 0) {
            List<Company> list = companyService.selectByCompanySelectParam(param);
            list.forEach(company -> boList.add(new CompanyBo(company)));
        }
        RecordNumAndCompanyVo returnVo = new RecordNumAndCompanyVo(recordNum, boList);
        baseVo.setData(returnVo);
        return baseVo;
    }

    @ResponseBody
    @ApiOperation(value = "根据id查询公司信息",
            notes = "1. 必填： id; " +
                    "2. 返回公司信息； ")
    @RequestMapping(value = "select/selectById", method = RequestMethod.GET)
    public BaseVo selectById(@RequestParam String id) {
        BaseVo baseVo = new BaseVo();
        if (StringUtils.isBlank(id) || !StringUtils.isNumeric(id)
                || Long.valueOf(id).equals(0L)) {
            baseVo.setCode(Constant.RESPONSE_PARAM_ERROR_CODE);
            baseVo.setMsg(Constant.RESPONSE_PARAM_ERROR_MSG);
            return baseVo;
        }
        Company company = companyService.selectById(Long.valueOf(id));
        List<CompanyBo> boList = new ArrayList<>();
        if (company != null) {
            boList.add(new CompanyBo(company));
        }
        RecordNumAndCompanyVo returnVo = new RecordNumAndCompanyVo(1, boList);
        baseVo.setData(returnVo);
        return baseVo;
    }

}